﻿using System.Text;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;

namespace Management.HttpApi.Host.Extensions
{
    public static class AuthenticationExtensions
    {
        public static void AddAuthenticationService(this IServiceCollection services, IConfiguration configuration)
        {
            var Issurer = configuration["Jwt:Issuer"];  //发行人
            var Audience = configuration["Jwt:Audience"];       //受众人
            var secretCredentials = configuration["Jwt:SecretCredentials"];   //密钥

            //配置认证服务
            services.AddAuthentication(x =>
            {
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(o =>
            {
                o.TokenValidationParameters = new TokenValidationParameters
                {
                    //是否验证发行人
                    ValidateIssuer = true,
                    ValidIssuer = Issurer,//发行人
                    //是否验证受众人
                    ValidateAudience = true,
                    ValidAudience = Audience,//受众人
                    //是否验证密钥
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(secretCredentials)),

                    ValidateLifetime = true, //验证生命周期
                    RequireExpirationTime = true, //过期时间
                };
            });
        }
    }
}
